import Echo from "laravel-echo";
import Pusher from "pusher-js";
import { shallowRef } from "vue";
import { AuthStorage } from "@/utils/auth";

window.Pusher = Pusher;

export const useEchoStore = defineStore("echo", () => {
  const echo = shallowRef<Echo<"reverb">>();

  const initEcho = () => {
    const accessToken = AuthStorage.getAccessToken();

    echo.value = new Echo({
      broadcaster: "reverb",
      key: import.meta.env.VITE_REVERB_APP_KEY,
      wsHost: import.meta.env.VITE_REVERB_HOST,
      wsPort: import.meta.env.VITE_REVERB_PORT ?? null,
      wssPort: import.meta.env.VITE_REVERB_PORT ?? null,
      forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? "https") === "https",
      enabledTransports: ["ws", "wss"],
      authEndpoint: `${import.meta.env.VITE_APP_API_URL}/broadcasting/auth`,
      auth: {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      },
    });
  };

  return {
    echo,
    initEcho,
  };
});
